package swu.cx.learning_10_17

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.widget.LinearLayout

class TabBar:LinearLayout {
    var current = 0
    var itemList:Array<itemModel> = emptyArray()
        set(value) {
            field = value
            update()
        }
    val bottomBars = mutableListOf<BottomBar>()

    var count = 0
    constructor(context: Context):super(context){
        init()
    }

    constructor(context: Context, attrs: AttributeSet):super(context,attrs){
        parseAttr(attrs)
        init()
    }
    private fun init() {
        orientation = HORIZONTAL
        gravity = Gravity.CENTER_VERTICAL
        for (i in 0 until count){
            BottomBar(context).also {
                val lp = LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT
                ).apply {

                    weight = 1f
                }
                it.selectCallback = {index->
                    //还原
                    bottomBars[current].mSelected = false
                    current = index
                }
                addView(it,lp)
                bottomBars.add(it)
            }
        }

    }


    private fun parseAttr(attrs: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attrs,R.styleable.TabBar)
        count = typedArray.getInt(R.styleable.TabBar_count,0)
        typedArray.recycle()
    }
    private fun update(){
        for ((i,item) in bottomBars.withIndex()){
           val model = itemList[i]
            item.bgPic = model.normalIcon
            item.selectIcon = model.selectIcon
            item.normalColor = model.normalColor
            item.selectColor = model.selectColor
            item.Bottomtext = model.text
            item.mSelected = model.selected
            item.index = i
        }
    }
}